package org.karelun.gef.commands;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.ui.IEditorPart;
import org.karelun.gef.model.DiagramModel;
import org.karelun.gef.model.Node;

public class PasteNodeCommand extends AbstractCommand {

	private List<Node> copyList = null;

	private List<Node> pasteList = null;

	private IEditorPart editor;

	private DiagramModel diagram = null;

	@SuppressWarnings("unchecked")
	public PasteNodeCommand(IEditorPart editor) {
		this.editor = editor;
		Object contents = Clipboard.getDefault().getContents();
		copyList = (List<Node>) contents;
	}

	@Override
	public boolean canExecute() {
		if (copyList == null || copyList.isEmpty())
			return false;
		return true;
	}

	public void execute() {
		if (!canExecute())
			return;
		if (pasteList == null)
			pasteList = new ArrayList<Node>();

		for (Node node : copyList) {
			if (diagram == null)
				diagram = node.getDiagram();
			Node clone = (Node) node.clone();
			Point loc = node.getLocation();
			Dimension size = node.getSize();
			Point point = new Point(loc.x + size.width + 10, loc.y);
			clone.setLocation(point);
			diagram.addNode(clone);
			pasteList.add(clone);
		}

	}

	public boolean canUndo() {
		if (pasteList == null || pasteList.isEmpty())
			return false;
		return true;
	}

	public void redo() {
		execute();
	}

	public void undo() {
		if (!canUndo())
			return;
		for (Node node : pasteList) {
			if (editor == null)
				return;
			diagram.removeNode(node);
		}
	}
}
